//
//  SocialViewController.swift
//  iModern
//
//  Created by Ralf on 6/2/15.
//  Copyright (c) 2015 com.starlooking. All rights reserved.
//

import UIKit

class SocialViewController: TableViewController
{
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    var searchButton:                UIBarButtonItem?
    var contactTypeSegmentedControl: UISegmentedControl?
    var contacts    = NSMutableArray()
    var end         = false
    var max         = 0
    var offset      = 0

    override func viewDidLoad()
    {
        super.viewDidLoad()

        self.tableView.registerNib(UINib(nibName: "SocialViewContactCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "CONTACT")
        self.tableView.registerNib(UINib(nibName: "SocialViewArticlesPreviewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "PREVIEW")

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()

    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func viewWillAppear(animated: Bool)
    {
        appDelegate.rootController.navigationItem.titleView = nil; appDelegate.rootController.navigationItem.leftBarButtonItem = nil; appDelegate.rootController.navigationItem.rightBarButtonItem = nil; initSearchButton()
        initContactTypeSegmentedControl()
        loadData()
    }
    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int
    {
        // #warning Potentially incomplete method implementation.
        // Return the number of sections.
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        // #warning Incomplete method implementation.
        // Return the number of rows in the section.
        return contacts.count * 2
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let mode = indexPath.row % 2
        if mode == 0
        {
            let cell = tableView.dequeueReusableCellWithIdentifier("CONTACT", forIndexPath: indexPath) as! SocialViewContactCell
            cell.setData(contacts[indexPath.row / 2] as! [String:AnyObject])
            return cell
        }
        else
        {
            let cell     = tableView.dequeueReusableCellWithIdentifier("PREVIEW", forIndexPath: indexPath) as! SocialViewArticlesPreviewCell
            let contact  = contacts[indexPath.row / 2] as! [String:AnyObject]
            let articles = contact["articles"] as? [[String:AnyObject]]
            cell.setData(articles)
            return cell
        }
    }


    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        let index   = indexPath.row / 2
        let item    = contacts[index] as! NSDictionary
        var contact = NSDictionary()

        if item.count > 1
        {
            contact = item["contact"] as! NSDictionary
        }
        else
        {
            contact = item as NSDictionary
        }

        let controller = OtherProfileViewController()
        let userName   = contact["userName"] as! String
        controller.loadDataByUserName(userName)
        self.pushViewController(controller)
    }

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
    {
        if indexPath.row % 2 == 0
        {
            return UIScreen.mainScreen().bounds.width / 5
        }
        else
        {
            return UIScreen.mainScreen().bounds.width / 5
        }
    }

    func initSearchButton()
    {
        if searchButton == nil
        {
            let image = UIImage(named: "Search-Small.png")!.imageWithRenderingMode(.AlwaysOriginal)
            searchButton = UIBarButtonItem(image: image, style: .Plain, target: self, action: "search:")
        }

        appDelegate.rootController.navigationItem.leftBarButtonItem = searchButton;
    }

    func initContactTypeSegmentedControl()
    {
        if contactTypeSegmentedControl == nil
        {
            contactTypeSegmentedControl = UISegmentedControl(items: ["热门", "关注", "粉丝"])
            contactTypeSegmentedControl!.tintColor = UIColor.darkGrayColor()
            contactTypeSegmentedControl!.frame = CGRectMake(0, 0, 220, 28)
            contactTypeSegmentedControl!.selectedSegmentIndex = 0
            contactTypeSegmentedControl!.addTarget(self, action: "segmentSelected:", forControlEvents: .ValueChanged)
        }

        appDelegate.rootController.navigationItem.titleView = contactTypeSegmentedControl
    }

    @IBAction func search(sender: AnyObject)
    {
        let controller = ContactSearchViewController()
        self.pushViewController(controller)
    }

    @IBAction func segmentSelected(sender: AnyObject)
    {
        reloadData(sender)
    }

    func loadData()
    {
        switch contactTypeSegmentedControl!.selectedSegmentIndex
        {
        case 0:
            loadTopContacts()
        case 1:
            loadFollowing()
        default:
            loadFollower()
        }
    }

    func loadTopContacts()
    {
        if end
        {
            return
        }

        let rs = appDelegate.contactManager.queryTopContact(max, offset: offset)

        if self.verifyResutSet(rs)
        {
            if rs.isEmpty()
            {
                end = true
                return
            }

            contacts.addObjectsFromArray(rs.toArray())

            offset = contacts.count
        }

        self.tableView.reloadData()
    }

    func loadFollowing()
    {
        if end
        {
            return
        }

        let rs = appDelegate.contactManager.queryFollowing(max, offset: offset)

        if self.verifyResutSet(rs)
        {
            if rs.isEmpty()
            {
                end = true
                return
            }
            contacts.addObjectsFromArray(rs.toArray())

            offset = contacts.count
        }
        self.tableView.reloadData()
    }

    func loadFollower()
    {
        if end
        {
            return
        }

        let rs = appDelegate.contactManager.queryFollower(max, offset: offset)

        if self.verifyResutSet(rs)
        {
            if rs.isEmpty()
            {
                end = true
                return
            }
            contacts.addObjectsFromArray(rs.toArray())

            offset = contacts.count
        }
        self.tableView.reloadData()
    }

    override func reloadData(sender: AnyObject!)
    {
        contacts.removeAllObjects()
        offset = 0
        end = false
        loadData()
        super.reloadData(sender)
    }
}
